﻿
Vue.component('code-mirror', {
    template: ' <textarea ref="mycode" v-bind:class="className" v-model="value"  :placeholder="placeholder" :style="styles"></textarea>',
    props: {
        name: {
            required: true,
            type: String
        },
        value: {
            required: true,
            type: String
        },
        width: {
            type: String,
            default: "100%"
        },
        height: {
            type: String,
            default:"100%"
        },
        placeholder: {
            type: String,
            default:'请输入正确的脚本'
        },
        themeName: {
            type: String,
            default: 'material'
        },
        className: {
            type: String,
            default: 'codesql'
        }
    },
    data: function (){
        return {
            styles: 'height:' + this.height + ";width:" + this.width+";",
            placeholder: this.placeholder
        };
    },
    watch: {
        value: function (val) {
            this.$emit('input', val);
        }
    },
    methods: {
     
    },
    mounted() {
        let that = this;
        let mime = 'text/x-mssql';
        let theme = this.themeName;//设置主题，不设置的会使用默认主题
        let editor = CodeMirror.fromTextArea(this.$refs.mycode, {
            mode: mime,//选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            theme: theme,
            // autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' },//自定义快捷键
            hintOptions: {//自定义提示选项
                tables: {
                    //users: ['name', 'score', 'birthDate'],
                    //countries: ['name', 'population', 'size']
                }
            }
        });

        editor.setSize(this.width, this.height);
        //代码自动提示功能，记住使用cursorActivity事件不要使用change事件，这是一个坑，那样页面直接会卡死
        editor.on('cursorActivity', function (e) {
            ////获取用户当前的编辑器中的编写的代码
            //var words = editor.getValue() + "";
            ////利用正则取出用户输入的所有的英文的字母
            //words = words.replace(/[a-z]+[\-|\']+[a-z]+/ig, '').match(/([a-z]+)/ig);
            ////将获取到的用户的单词传入CodeMirror,并在javascript-hint中做匹配
            //CodeMirror.ukeys = words;
            ////调用显示提示
            //editor.showHint();
        });

        editor.on("change", function (e) {
            that.$emit('input', e.getValue());
        });

       editor.addKeyMap({
            'Backspace': function (cm) {
                var ch = cm.getTokenAt(cm.getCursor());
               if (ch.type === 'keyword') {
                    cm.execCommand('delWordBefore');
                    cm.execCommand('delCharBefore');
                } else {
                    cm.execCommand('delCharBefore');
                }
            }
        });
    }
});